package com.manager.commons.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;

import org.slf4j.Logger;

import com.manager.commons.file.FileUtil;
import com.manager.commons.log.LogFactory;

public class FileUtils {

    protected static Logger logger = LogFactory.getLogger(FileUtils.class);

    /**
     * 根据路径删除文件或目录（包括子内容）
     *
     * @param path 要删除的文件或目录的路径
     * @return 删除成功返回true，否则返回false
     */
    public static boolean delete(String path) {


        if (path == null || path.trim().isEmpty()) {
            logger.info("路径不能为空");
            return false;
        }

        File file = new File(path);
        return delete(file);
    }

    /**
     * 删除文件或目录（包括子内容）
     *
     * @param file 要删除的File对象
     * @return 删除成功返回true，否则返回false
     */
    public static boolean delete(File file) {
        // 检查文件/目录是否存在
        if (!file.exists()) {
            logger.error("文件或目录不存在: " + file.getAbsolutePath());
            return false;
        }

        // 如果是目录，递归删除其子内容
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File subFile : files) {
                    // 递归删除子文件或子目录
                    if (!delete(subFile)) {
                        return false;
                    }
                }
            }
        }

        // 删除当前文件或空目录
        boolean deleted = file.delete();
        if (deleted) {
            if (file.isDirectory()) {
                logger.info("已删除目录: " + file.getAbsolutePath());
            } else {
                logger.error("已删除文件: " + file.getAbsolutePath());
            }
        } else {
            logger.error("无法删除: " + file.getAbsolutePath());
        }

        return deleted;
    }


    // 使用NIO方式重命名文件或目录
    public static boolean renameWithNIO(String sourcePath, String targetPath) {
        Path source = Paths.get(sourcePath);
        Path target = Paths.get(targetPath);
        try {
            // 移动文件（重命名本质是移动操作）
            // REPLACE_EXISTING 表示如果目标存在则替换
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
            logger.info("重命名成功: " + sourcePath + " -> " + targetPath);
            return true;
        } catch (IOException e) {
            logger.error("重命名失败: " + e.getMessage());
            return false;
        }
    }

    // 使用NIO删除文件或目录（忽略不存在的情况）
    public static boolean deleteIfExistsWithNIO(String pathStr) {
        Path path = Paths.get(pathStr);
        try {
            // deleteIfExists() 存在则删除，不存在返回false
            Files.deleteIfExists(path);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建文件夹
     *
     * @param folderPath 文件夹路径
     * @return 是否创建成功
     */
    public static boolean createFilesFolder(String folderPath) {
        boolean isCreated =  createFolder(folderPath);
        if (isCreated) {
            logger.info("文件夹创建成功: " + folderPath);
        } else {
            logger.error("文件夹创建失败: " + folderPath);
        }
        return isCreated;
    }

    /**
     * 创建文件夹
     *
     * @param folderPath 文件夹路径
     * @return 是否创建成功
     */
    public static boolean createFolder(String folderPath) {
        // 创建File对象
        File folder = new File(folderPath);
        // 判断文件夹是否已经存在
        if (folder.exists()) {
            logger.error("文件夹已存在: " + folderPath);
            return true;
        }
        // 创建文件夹，mkdirs()可以创建多级目录
        boolean isCreated = folder.mkdirs();
        if (isCreated) {
            logger.info("文件夹创建成功: " + folderPath);
        } else {
            logger.error("文件夹创建失败: " + folderPath);
        }
        return isCreated;
    }

    /**
     * 复制文件
     *
     * @param thumbnailPath
     * @param uploadFilePath
     * @param id
     * @return
     */
    public static String copyFile(String thumbnailPath, String uploadFilePath, String id) {
        if (StringUtil.isNotEmpty(thumbnailPath)) {
            String filePath = "/file/upload/";
            String fssFilePath = uploadFilePath.concat(filePath).concat(id);
            File fssFile = new File(fssFilePath);
            if (!fssFile.exists()) {
                fssFile.mkdirs();
            }
            String ymd = DateUtil.format(new Date(), "yyyyMMdd");
            String ymdFilePath = fssFilePath.concat("/").concat(ymd);
            File ymdFile = new File(ymdFilePath);
            if (!ymdFile.exists()) {
                ymdFile.mkdirs();
            }
            String fileExt = FileUtil.getFileSuffix(thumbnailPath);
            String newFileName = id + "." + fileExt;
            String newFilePath = filePath + id + "/" + ymd + "/" + newFileName;
            try {
                FileUtil.copyFile(new File(uploadFilePath + thumbnailPath), new File(ymdFilePath + "/" + newFileName));
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            return newFilePath;
        }
        return thumbnailPath;
    }

    /**
     * 复制文件
     *
     * @param thumbnailPath
     * @param uploadFilePath
     * @return
     */
    public static String copyFileToFile(String thumbnailPath, String uploadFilePath, String filePath) {
        if (StringUtil.isNotEmpty(thumbnailPath)) {
            String newFilePath = thumbnailPath.replace("/temp/", filePath);
            try {
                String newFileName = newFilePath.substring((newFilePath.lastIndexOf("/") + 1));
                System.out.println("fileName:" + newFileName);
                String path = newFilePath.substring(0, newFilePath.indexOf(newFileName) - 1);
                System.out.println("path:" + path);
                File newFile = new File(uploadFilePath + path);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                FileUtil.copyFile(new File(uploadFilePath + thumbnailPath), new File(uploadFilePath + newFilePath));
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            }
            return newFilePath;
        }
        return thumbnailPath;
    }

    /**
     * 文件路径替换后的名字
     *
     * @param filePath
     * @param newName
     * @return
     */
    public static String getFileRename(String filePath, String newName) {
        if (StringUtil.isNotEmpty(filePath)) {
            String name = filePath.substring(filePath.lastIndexOf("/") + 1);
            int i = name.lastIndexOf(".");
            String ext = "";
            if (i >= 0) ext = name.substring(i);
            return filePath.replace(name, newName + ext);
        }
        return "";
    }

    public static String getFileExt(String fileName) {
        return fileName.substring((fileName.lastIndexOf(".") + 1)).toLowerCase();
    }

}